// 判断浏览器
const judgeBrowser = () => {
  var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
  if (userAgent.indexOf("Opera") > -1) { //判断是否Opera浏览器
    return "Opera"
  }
  if (userAgent.indexOf("Firefox") > -1) { //判断是否Firefox浏览器
    return "FF";
  }
  if (userAgent.indexOf("Chrome") > -1) { //判断是否为谷歌浏览器
    return "Chrome";
  }
  if (userAgent.indexOf("Safari") > -1) { //判断是否Safari浏览器
    return "Safari";
  }
  if (userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1 && !isOpera) { //判断是否IE浏览器
    return "IE";
  }
}

const bindDrag = ($dom, $header, cfg) => {
  const w = $dom.offsetWidth || parseInt($dom.style.width),
    h = $dom.offsetHeight || parseInt($dom.style.height),
    W = document.documentElement.clientWidth,
    H = document.documentElement.clientHeight;
  if (cfg && cfg.left && cfg.top) {
    $dom.style.left = cfg.left;
    $dom.style.top = cfg.top;
  } else {
    $dom.style.left = (W - w) / 2 + 'px';
    $dom.style.top = (H - h) / 2 - 10 + 'px';
  }

  if (!$header) return false;

  window.dragAbout = {
    enabled: false,
    dom: $dom,
    w: w,
    h: h,
    x: 0,
    y: 0,
    l: 0,
    t: 0,
  };
  $header.onmousedown = function (e) {
    window.dragAbout = {
      enabled: true,
      dom: $dom,
      w: w,
      h: h,
      x: e.clientX,
      y: e.clientY,
      l: $dom.offsetLeft,
      t: $dom.offsetTop,
    };
  };
  window.onmousemove = function (e) {
    if (!window.dragAbout.enabled) return false;
    const w = window.dragAbout.w,
      h = window.dragAbout.h,
      W = document.documentElement.clientWidth,
      H = document.documentElement.clientHeight,
      l = window.dragAbout.l,
      t = window.dragAbout.t,
      x = window.dragAbout.x,
      y = window.dragAbout.y;
    var nx = e.clientX;
    var ny = e.clientY;
    var nl = nx - (x - l);
    var nt = ny - (y - t);
    if (nl <= 0) nl = 0;
    if (nl >= (W - w)) nl = (W - w);
    if (nt < 0) nt = 0;
    if (nt >= (H - h)) nt = (H - h);
    window.dragAbout.dom.style.left = nl + 'px';
    window.dragAbout.dom.style.top = nt + 'px';
  };
  window.onmouseup = function () {
    window.dragAbout = {};
  }
};


const str2Hex=(str)=> {
  str = str.toString();
  let hex = '';
  for (let i = 0; i < str.length; i++) {
    const code = str.charCodeAt(i),
      num = Math.floor(Math.random() * 16);
    const sum = code + num;
    hex += sum.toString(36) + num.toString(16)
  }
  return String.fromCharCode(Math.floor(Math.random() * 25) + 97) + hex;
};

/**
 *************************************************************************
 * html：页面元素
 *
 *************************************************************************
 */

// 更改页面title ，默认前面追加 txx -，isReplace 完全替换
const renewTitle = (title, isReplace) => {
  document.getElementsByTagName("title")[0].innerText = title || '';
};

/**
 *************************************************************************
 * 数据处理：
 *
 *************************************************************************
 */

const typeOf = (data) => {
  const types = {
    '[object Array]': 'array',
    '[object Object]': 'obj',
    '[object Number]': 'number',
    '[object String]': 'string',
    '[object Undefined]': 'undefined',
    '[object Function]': 'function',
    '[object Null]': 'null',
  };
  return types[Object.prototype.toString.call(data)]
};

const isJsonStr = (string, returnJson) => {
  let flag = false;
  try {
    JSON.parse(string);
    flag = true;
  } catch (e) {
    return returnJson ? string : false;
  }
  return returnJson ? (flag ? JSON.parse(string) : string) : flag;
};

const randomStr = (bit, length) => {
  var result = '';
  for (var i = 0; i < length; i++) {
    result += Math.floor(Math.random() * bit).toString(bit);
  }
  return result.toUpperCase();
};


//导出表格
const downExcel = (tabName, tabContent) => {
  tabName = tabName || 'default';
  tabContent = tabContent || '<table></table>';
  var excel = `
            <html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:x='urn:schemas-microsoft-com:office:excel' xmlns='http://www.w3.org/TR/REC-html40'>
                <head>
                    <meta charset='UTF-8'>
                </head>
                <body>
                    ${tabContent}
                </body>
            </html>
            `;
  const blob = new Blob([excel], {type: 'application/vnd.ms-excel'});
  const url = window.URL.createObjectURL(blob);

  const a = document.createElement('a');
  a.href = url;
  a.style.display = 'none';
  a.download = tabName + '.xls';
  a.click();
};


/**
 *************************************************************************
 * localStorage： get,set,del
 *
 *************************************************************************
 */

const cache = {
  isJsonStr(str) {
    try {
      JSON.parse(str);
    } catch (e) {
      return false;
    }
    return true;
  },
  get(key) {
    const storage = window.localStorage.getItem(key);
    return storage && this.isJsonStr(storage) ? JSON.parse(storage) : storage;
  },
  set(key, val) {
    this.del(key);// 解决IOS出现的一些BUG
    window.localStorage.setItem(key, val && ['obj', 'array'].indexOf(typeOf(val)) > -1 ? JSON.stringify(val) : val);
  },
  del(key) {
    window.localStorage.removeItem(key);

  }
};


/**
 *************************************************************************
 * 提示信息： msg alert submit loading
 *
 *************************************************************************
 */

/**
 * @param cfg
 * title:''
 * icon:[0|1] 1:success 0:fail
 * cont:'html'
 * time:auto close time
 */

const msg = (cfg) => {
  if (!cfg || document.querySelectorAll('.kkMsg').length > 0) return false;
  const kkMsg = document.createElement('div');
  kkMsg.className = 'kkMsg noBlueBg';
  kkMsg.setAttribute('idx', new Date().getTime().toString());
  kkMsg.innerHTML = `
      <div class="kkMsg-box">
        <div class="kkMsg-body">
          <div class="kkMsg-icon">
              ${!('icon' in cfg) || cfg['icon'] ? '<span class="el-icon el-icon-success"></span>' : '<span class="el-icon el-icon-warning"></span>'}
          </div>
          <div class="kkMsg-cont">
            ${cfg['cont'] || ''}
          </div>
        </div>
      </div>
    `;
  document.body.append(kkMsg);
  setTimeout(function () {
    kkMsg.remove();
  }, cfg.time || 2000);
};

/**
 * @param cfg
 * title:''
 * icon:[0|1] 1:alert 0:confirm 带 cancal btn
 * btn0Txt/btn1Txt:'确定'/'取消'
 * cont:'html'
 * callback:btn0 callback
 */
const alert = (cfg) => {
  if (!cfg || document.querySelectorAll('.kkAlert').length > 0) return false;
  const kkAlert = document.createElement('div');
  kkAlert.className = 'kkAlert noBlueBg';
  kkAlert.setAttribute('idx', new Date().getTime().toString());
  kkAlert.innerHTML = `
      <div class="kkAlert-box">
        <div class="kkAlert-header">
          ${cfg.title || '提示'}
          <span class="kkAlert-close">×</span>
        </div>
        <div class="kkAlert-body">
          <div class="kkAlert-icon">
            ${!('icon' in cfg) || cfg['icon'] ? '<span class="el-icon el-icon-warning"></span>' : '<span class="el-icon el-icon-question"></span>'}
          </div>
          <div class="kkAlert-cont">
            ${cfg['cont'] || ''}
          </div>
        </div>
        <div class="kkAlert-footer">
          <button type="button" class="kkAlert-submit el-button el-button--primary el-button--mini"><span>${cfg['btn0Txt'] || '确定'}</span></button>
          ${'icon' in cfg && !cfg['icon'] ? `<button type="button" class="kkAlert-cancal el-button el-button--default el-button--mini"><span>${cfg['btn1Txt'] || '取消'}</span></button>` : ''}
        </div>
      </div>
  `;
  document.body.append(kkAlert);
  kkAlert.querySelector('.kkAlert-close').addEventListener('click', function () {
    kkAlert.parentNode.removeChild(kkAlert);
  });

  kkAlert.querySelector('.kkAlert-submit').addEventListener('click', function () {
    if (typeof cfg['callback'] === 'function') cfg['callback']();
    kkAlert.parentNode.removeChild(kkAlert);
  });

  if ('icon' in cfg && !cfg['icon']) {
    kkAlert.querySelector('.kkAlert-cancal').addEventListener('click', function () {
      if (typeof cfg['cancelCallback'] === 'function') cfg['cancelCallback']();
      kkAlert.parentNode.removeChild(kkAlert);
    });
  }

  bindDrag(kkAlert.querySelector('.kkAlert-box'), kkAlert.querySelector('.kkAlert-header'));
};

const submit = (cfg, callback) => {
  const submit = document.createElement('div');
  submit.className = 'mySubmit noBlueBg';
  const idx = new Date().getTime();
  submit.setAttribute('idx', idx);
  submit.innerHTML = `
      <div class="mySubmit-box">
        <div class="mySubmit-header">
          ${cfg && cfg.title || '提示'}
          <span class="mySubmit-close">×</span>
        </div>
        <div class="mySubmit-body">
            ${cfg.file ?
    `<input type="file" accept=".csv, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" class="mySubmit-input" placeholder="${cfg.placeholder || ''}">`
    : (cfg.image ? `<input type="file" accept="image/*," class="mySubmit-input" placeholder="${cfg.placeholder || ''}">` : `<input type="text" class="mySubmit-input" placeholder="${cfg.placeholder || ''}">`)
    }
        </div>
        <div class="mySubmit-footer">
          <button type="button" class="el-button el-button--primary el-button--mini"><span>确定</span></button>
          <button type="button" class="el-button el-button--default el-button--mini"><span>取消</span></button>
        </div>
      </div>
  `;
  document.body.append(submit);
  submit.getElementsByClassName('mySubmit-close')[0].addEventListener('click', function () {
    submit.remove();
  });
  submit.getElementsByClassName('el-button--primary')[0].addEventListener('click', function () {
    let $input = submit.querySelectorAll('.mySubmit-input')[0];
    let val;
    if (cfg.file || cfg.image) {
      var file = $input.files[0];
      if (!file) {
        msg({cont: '没有选择文件！', icon: 0, time: 1000});
        return false;
      }
      val = new FormData();
      val.append('file', file)
    }else {
      val = $input.value.trim();
      if (!val) {
        msg({cont: cfg.nullMsg || '内容不能为空！', icon: 0, time: 1000});
        return false;
      }
    }
    if (typeof callback === 'function') {
      callback(val);
    }
    submit.remove();
  });
  submit.getElementsByClassName('el-button--default')[0].addEventListener('click', function () {
    submit.remove();
  });
  bindDrag(submit.getElementsByClassName('mySubmit-box')[0], submit.getElementsByClassName('mySubmit-header')[0]);
};

const loading = {
  show(txt) {
    const myLoading = document.createElement('div');
    myLoading.className = 'myLoading';
    const idx = new Date().getTime().toString();
    myLoading.setAttribute('idx', idx);
    myLoading.innerHTML = `
      <div class="myLoading-box">
        <div class="${txt ? 'myLoading-body haveTxt' : 'myLoading-body'}">
          <div class="myLoading-icon">
            <div class="myLoading-dots">
              <div></div>
              <div></div>
              <div></div>
              <div></div>
              <div></div>
            </div>
          </div>
          <div class="myLoading-cont">
            ${txt || ''}
          </div>
        </div>
      </div>
    `;
    document.body.append(myLoading);
    return idx;
  },

  hide(idx) {
    if (idx) {
      const myLoading = document.querySelector(".myLoading[idx='" + idx + "']");
      myLoading && myLoading.remove();
    } else {
      const myLoadings = document.querySelectorAll(".myLoading");
      if (myLoadings && myLoadings.length > 0) {
        Array.from(myLoadings).forEach(myLoading => {
          myLoading.remove();
        });
      }
    }
  }
};

/**
 *  深蓝色加载
 */
const loading_deepBlue = {
  show(txt) {
    let myLoading = document.querySelector(".kkLoading_deepBlue");
    myLoading = document.createElement('div');
    myLoading.className = 'kkLoading_deepBlue noBlueBg';
    myLoading.innerHTML = `
      <div class="img_big">
      </div>
      <div class="img_small">
      </div>
      <div class="txt"><span>${txt || '数据加载中'}</span></div>
    `;
    document.body.appendChild(myLoading);
  },
  hide() {
    const myLoading = document.querySelector(".kkLoading_deepBlue");
    myLoading && myLoading.remove();
  }

};

const dialog = (cfg) => {
  const dialog = document.createElement('div');
  dialog.className = 'myDialog noComp noBlueBg';
  const idx = new Date().getTime();
  dialog.setAttribute('idx', idx);

  dialog.innerHTML = `
<!--      <div class="myDialog-bg"></div>-->
      <div class="myDialog-box" style="width:${cfg.width};height:${cfg.height}">
      <span class="myDialog-close circle">×</span>
      <div class="myDialog-cont">
        ${cfg.cont}
      </div>
    </div>
  `;
  document.body.append(dialog);
  if (typeof cfg.successFn === "function") {
    cfg.successFn();
  }
  dialog.getElementsByClassName('myDialog-close')[0].addEventListener('click', function () {
    dialog.parentNode.removeChild(dialog);
  });
  return idx;
};

const dialog2 = (cfg) => {
  const dialog = document.createElement('div');
  dialog.className = 'myDialog noComp noBlueBg';
  const idx = new Date().getTime();
  dialog.setAttribute('idx', idx);

  dialog.innerHTML = `
      <div class="myDialog-bg"></div>
      <div class="myDialog-box" style="width:${cfg.width};height:${cfg.height}">
      <span class="myDialog-close circle">×</span>
      <div class="myDialog-cont">
        ${cfg.cont}
      </div>
    </div>
  `;
  document.body.append(dialog);
  if (typeof cfg.successFn === "function") {
    cfg.successFn();
  }
  dialog.getElementsByClassName('myDialog-close')[0].addEventListener('click', function () {
    dialog.parentNode.removeChild(dialog);
  });
  return idx;
};


const gis2Bmap = (gis) => {
  const lng = gis[0], lat = gis[1];
  let x_pi = 3.14159265358979324 * 3000.0 / 180.0;
  let x = lng;
  let y = lat;
  let z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
  let theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
  let lngs = z * Math.cos(theta) + 0.0065;
  let lats = z * Math.sin(theta) + 0.006;

  return [lngs, lats]
};

export default {
  judgeBrowser,
  bindDrag,
  isJsonStr,
  randomStr,
  typeOf,
  renewTitle,
  cache,
  downExcel,
  msg,
  alert,
  submit,
  loading,
  loading_deepBlue,
  dialog,
  dialog2,
  gis2Bmap,
  str2Hex
}
